import { AfterViewInit, ChangeDetectionStrategy, Component, Injector, ViewChild } from '@angular/core';
import { SFComponent, SFSchema, SFValueChange } from '@delon/form';
import { SFButton, type SFValue } from '@delon/form/src/interface';
import type { FormProperty, PropertyGroup } from '@delon/form/src/model/form.property';
import { ModalHelper } from '@delon/theme';
import { BaseOfUserComponent } from '@pages/user/_base';
import { UpdateAvatarComponent } from '@pages/user/profile/update-avatar/update-avatar.component';
import { UserForm, UserInfoVO, UserVO } from '@types';

import { UserProfileService } from './user-profile.service';

@Component({
    selector: 'app-profile',
    templateUrl: './profile.component.html',
    styleUrls: ['./profile.component.less'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProfileComponent extends BaseOfUserComponent implements AfterViewInit {
    @ViewChild('passWord', { static: false }) passWord!: SFComponent;

    profileLoading: boolean = false;
    userProfileInfo?: UserInfoVO;

    updateProfileItem?: UserVO;

    updateProfileSchema: SFSchema = {
        properties: {
            nickName: {
                type: 'string',
                title: '用户昵称'
            },
            phonenumber: {
                type: 'string',
                title: '手机号码',
                format: 'mobile',
                ui: {}
            },
            email: {
                type: 'string',
                title: '邮箱',
                format: 'email',
                ui: {}
            },
            sex: {
                type: 'string',
                title: '性别',
                enum: [
                    { label: '男', value: '0' },
                    { label: '女', value: '1' }
                ],
                ui: {
                    widget: 'radio',
                    styleType: 'default',
                    buttonStyle: 'solid'
                }
            }
        },
        required: ['nickName', 'phonenumber', 'email'],
        ui: {
            spanLabelFixed: 90
        }
    };

    updatePassWordSchema: SFSchema = {
        properties: {
            oldPassword: {
                type: 'string',
                title: '旧密码',
                ui: {
                    widget: 'password',
                    placeholder: '请输入旧密码'
                }
            },
            newPassword: {
                type: 'string',
                title: '新密码',
                ui: {
                    widget: 'password',
                    placeholder: '请输入新密码'
                },
                maxLength: 20,
                minLength: 6
            },
            confirmPassword: {
                type: 'string',
                title: '确认密码',
                ui: {
                    widget: 'password',
                    placeholder: '请确认新密码',
                    validator: (value: SFValue, formProperty: FormProperty, form: PropertyGroup) => {
                        if (value !== form?.value?.newPassword) {
                            return [{ keyword: 'required', message: '两次输入的密码不一致！' }];
                        }
                        return [];
                    }
                }
            }
        },
        required: ['oldPassword', 'newPassword', 'confirmPassword'],
        ui: {
            spanLabelFixed: 90
        }
    };

    get avatar() {
        if (!!this.userProfileInfo?.user?.avatar) {
            return this.userProfileInfo.user.avatar;
        }
        return '/assets/profile.jpg';
    }

    constructor(
        protected override injector: Injector,
        protected upSrv: UserProfileService
    ) {
        super(injector);
    }
    ngAfterViewInit() {
        this.profileLoading = true;
        this.cdRef.detectChanges();
        this.upSrv.getUserProfile().subscribe({
            next: res => {
                this.userProfileInfo = res.data;
                this.updateProfileItem = res.data?.user;
                this.profileLoading = false;
                this.cdRef.detectChanges();
            }
        });
    }

    /**
     * 更新头像
     */
    updateAvatar() {
        this.modal
            .creatStaticModal(
                UpdateAvatarComponent,
                {
                    avatar: this.avatar
                },
                'lg',
                {
                    nzTitle: '修改头像'
                }
            )
            .subscribe(res => {});
    }

    /**
     * 更新信息
     * @param params
     */
    updateUserProfile(params: any) {
        this.upSrv.updateUserProfile(params).subscribe(res => {
            console.log(res);
        });
    }

    updatePassWord(params: any) {
        this.upSrv.updateUserPwd(params).subscribe(res => {
            console.log(res);
        });
    }

    passwordValueChange(event: SFValueChange) {
        if (event.path === '/newPassword') {
            if (event.value.confirmPassword !== event.pathValue) {
                this.passWord.getProperty('/confirmPassword')?.setErrors({ message: '两次输入的密码不一致！' });
            }
            if (event.value.confirmPassword === event.pathValue) {
                this.passWord.getProperty('/confirmPassword')?.setErrors();
            }
        }
    }

    /**
     * 关闭页面
     */
    closePage() {}
}
